package com.sky.controller.user;

import com.sky.constant.JwtClaimsConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.properties.JwtProperties;
import com.sky.result.Result;
import com.sky.service.WxUserService;
import com.sky.utils.JwtUtil;
import com.sky.vo.UserLoginVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.security.auth.login.LoginException;
import java.io.IOException;
import java.util.HashMap;


@Slf4j
@RestController
@RequestMapping("/user/user")
public class UserController {
    private final JwtProperties jwtProperties;
    private final WxUserService wxUserService;
    @Autowired
    public UserController(WxUserService wxUserService,JwtProperties jwtProperties) {
        this.jwtProperties = jwtProperties;
        this.wxUserService = wxUserService;
    }


    @PostMapping("/login")
    public Result<UserLoginVO> wxLogin(@RequestBody UserLoginDTO userLoginDTO) throws IOException, LoginException {
        System.out.println(userLoginDTO);
       User user =  wxUserService.wxLogin(userLoginDTO.getCode());
       // 为微信用户创建toke
        HashMap<String, Object> clams = new HashMap<>();
        clams.put(JwtClaimsConstant.USER_ID,user.getId());
        String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(),jwtProperties.getAdminTtl(),clams);
        UserLoginVO userVo = UserLoginVO
                                .builder()
                                .id(user.getId())
                                .openid(user.getOpenid())
                                .token(token)
                                .build();
        return Result.success(userVo);
    }

}
